package cn.hniu.controller;

import cn.hniu.mapper.TextPostsMapper;
import cn.hniu.pojo.TextPosts;
import cn.hniu.pojo.util.PageAll;
import cn.hniu.pojo.util.Result;
import cn.hniu.service.TextPostsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/textposts")
public class TextPostsController {

    @Autowired
    private TextPostsService textPostsService;
    @Autowired
    private TextPostsMapper textPostsMapper;

    //查询帖子
    @GetMapping("/{data}/{begin}/{size}")
    @ResponseBody
    public Result findTextPosts(@PathVariable("data") String data,
                                @PathVariable("begin") Integer begin,
                                @PathVariable("size") Integer size){

        if(textPostsService.findTextPosts(data,begin-1,size).size()==0){
            return new Result(400,"没有查到");
        }else {
            int list = textPostsMapper.selectCount(new QueryWrapper<TextPosts>().like("tp_title", data));
            PageAll pageAll=new PageAll();
            pageAll.setCurrent(begin);
            pageAll.setPages((int)Math.ceil((double)list/size));
            pageAll.setSize(size);
            pageAll.setTotals(list);
            pageAll.setTextPostsList(textPostsService.findTextPosts(data,begin-1,size));
            return new Result(200,pageAll);
        }
    }

    //修改帖子
    @PutMapping("/updateTextPosts")
    @ResponseBody
    public Result updateTextPosts(@RequestBody TextPosts textPosts){
        if(textPostsService.updateTextPosts(textPosts)>0){
            return new Result(200,"修改成功");
        }else
        {
            return new Result(400,"修改失败");
        }
    }

    //删除帖子
    @PutMapping("/deleteTextPosts/{id}")
    @ResponseBody
    public Result deleteTextPosts(@PathVariable("id") Integer id){
        if(textPostsService.deleteTextPosts(id)>0){
            return new Result(200,"删除成功");
        }else
        {
            return new Result(400,"删除失败");
        }
    }

    //查询帖子浏览量
    @GetMapping("/findTextPostsBytHot")
    public Result findTextPostsBytHot(){
        if(textPostsService.findTextPostsByflowrate().size()==0){
            return new Result(400,"没查到");
        }else {
            return new Result(200,textPostsService.findTextPostsByflowrate());
        }
    }

}
